package com.wang.tool.trace;

import com.wang.tool.executor.transitivethreadcontext.ThreadContextTransferTool;
import com.wang.tool.util.SimpleLogUtil;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

/**
 * web工具bean注入
 *
 * @Author wangshaopeng
 * @Date 2021/1/7
 */
public class TraceRegister implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        AnnotationAttributes tooAttr = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(EnableTrace.class.getName()));

        Class<?> traceTransmitter = tooAttr.getClass("traceTransmitter");
        try {
            TraceTransmitter o = (TraceTransmitter) traceTransmitter.newInstance();
            TraceHolder.setTransmitter(o);
        } catch (Throwable e) {
            throw new IllegalArgumentException("traceTransmitter must has No-argument construction");
        }

        Class<?> traceBuilder = tooAttr.getClass("traceBuilder");
        try {
            TraceBuilder o = (TraceBuilder) traceBuilder.newInstance();
            TraceHolder.setTraceBuilder(o);
        } catch (Throwable e) {
            throw new IllegalArgumentException("traceBuilder must has No-argument construction");
        }

        ThreadContextTransferTool.addGlobalTransmitter(new TraceThreadContextTransmitter());
        SimpleLogUtil.info("[addGlobalTransmitter], TraceThreadContextTransmitter");
    }
}
